package top.crossrun.notify;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v4.content.LocalBroadcastManager;

import top.crossrun.net.api.ApiNet;
import top.crossrun.net.api.param.KVStringParam;

public class NotifyService extends Service implements NotifyMessageListener {

    String channelID = "9393";

    String channelName = "提醒通知";

    MessageReceiver messageReceiver;

    PhoneReceiver phoneReceiver;

    MyNotifyBroadcastReceiver notifyBroadcastReceiver;

    boolean checkMessage = true;
    boolean checkPhone = true;
    boolean checkNotification = true;

    public NotifyService() {
    }

    public void setCheckPhone(boolean checkPhone) {
        this.checkPhone = checkPhone;
        startForeground(9393, getNotification());
    }

    public void setCheckMessage(boolean checkMessage) {
        this.checkMessage = checkMessage;
        startForeground(9393, getNotification());
    }

    public void setCheckNotification(boolean checkNotification) {
        this.checkNotification = checkNotification;
        startForeground(9393, getNotification());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        startForeground(9393, getNotification());
        if (messageReceiver == null) {
            messageReceiver = new MessageReceiver(this);
            IntentFilter intentFilter1 = new IntentFilter();
            intentFilter1.addAction("android.provider.Telephony.SMS_RECEIVED");
            intentFilter1.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
            registerReceiver(messageReceiver, intentFilter1);

            phoneReceiver = new PhoneReceiver(this);
            IntentFilter intentFilter2 = new IntentFilter();
            intentFilter2.addAction("android.intent.action.PHONE_STATE");
            intentFilter2.addAction(Intent.ACTION_NEW_OUTGOING_CALL);
            intentFilter2.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
            registerReceiver(messageReceiver, intentFilter2);

            Intent intent1 = new Intent(this, MyNotificationListenerService.class);
            startService(intent1);

            notifyBroadcastReceiver = new MyNotifyBroadcastReceiver();
            IntentFilter intentFilter3 = new IntentFilter();
            intentFilter3.addAction(MyNotificationListenerService.ACTION);
            LocalBroadcastManager.getInstance(this).registerReceiver(notifyBroadcastReceiver, intentFilter3);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        SharedPreferences sp = getSharedPreferences("notify", Context.MODE_PRIVATE);
        checkMessage = sp.getBoolean("message", true);
        checkPhone = sp.getBoolean("phone", true);
        checkNotification = sp.getBoolean("notification", true);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(messageReceiver);
        unregisterReceiver(phoneReceiver);
        LocalBroadcastManager.getInstance(this).unregisterReceiver(notifyBroadcastReceiver);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return stub;
    }

    private Notification getNotification() {
        Notification.Builder builder = new Notification.Builder(this.getApplicationContext()); //获取一个Notification构造器
        Intent nfIntent = new Intent(this, MainActivity.class);

        builder.setContentIntent(PendingIntent.
                getActivity(this, 0, nfIntent, 0)) // 设置PendingIntent
                .setLargeIcon(BitmapFactory.decodeResource(this.getResources(),
                        R.mipmap.ic_launcher)) // 设置下拉列表中的图标(大图标)
                .setContentTitle("消息提醒工具") // 设置下拉列表里的标题
                .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
                .setContentText(String.format("短信=%s;  来电=%s;  读取通知=%s;", checkMessage ? "允许" : "", checkPhone ? "允许" : "不允许", checkNotification ? "允许" : "不允许")) // 设置上下文内容
                .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间
        Notification notification = builder.build(); // 获取构建好的Notification
        notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
        startForeground(110, notification);

        if (Build.VERSION.SDK_INT >= 26) {

            builder.setChannelId(channelID);

            NotificationChannel channel = new NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH);

            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            manager.createNotificationChannel(channel);
        }

        return builder.build();
    }

    @Override
    public void onAccpetMessage(String tag, String src, String message) {
        if ("短信".equals(tag) && !checkMessage) {
            return;
        }
        if ("来电".equals(tag) && !checkPhone) {
            return;
        }
        if ("通知".equals(tag) && !checkNotification) {
            return;
        }
        SharedPreferences sp = getSharedPreferences("notify", Context.MODE_PRIVATE);
        ApiNet.post(String.class)
                .setParam(new KVStringParam()
                        .addParam("type", tag)
                        .addParam("msg", String.format("%s-%s", src, message))
                        .setUrl(sp.getString("url", ""))
                )
                .http();
    }

    private NotifyServiceInterface.Stub stub = new NotifyServiceInterface.Stub() {
        @Override
        public void setCheckPhone(boolean checkPhone) throws RemoteException {
            NotifyService.this.setCheckPhone(checkPhone);
        }

        @Override
        public void setCheckMessage(boolean checkMessage) throws RemoteException {
            NotifyService.this.setCheckMessage(checkMessage);
        }

        @Override
        public void setCheckNotification(boolean checkNotification) throws RemoteException {
            NotifyService.this.setCheckNotification(checkNotification);
        }
    };

    class MyNotifyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null) {
                return;
            }
            onAccpetMessage(intent.getStringExtra("tag"), intent.getStringExtra("src"), intent.getStringExtra("message"));
        }
    }
}
